package com.xigua.basicsAndApplication;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashMap;
import java.util.Map;

/**
 * @author LiRongHua
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: redis 实现可重入锁
 * @date 2022/1/1222:41
 */
public class RedisWithReentrantLock {
    private ThreadLocal<Map<String,Integer>> lockers = new ThreadLocal();

    private Jedis jedis;
    private static JedisPool jedisPool;
    static {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(10);
        config.setMaxWaitMillis(30000);
        jedisPool = new JedisPool(config,"120.76.116.216",6379,3000,"xg123456");

    }





    public RedisWithReentrantLock(Jedis jedis){
        this.jedis = jedis;
    }

    private boolean _lock(String key){
        return jedis.set(key,"","nx","ex",5l) !=null;
    }

    private void _unlock(String key){
        jedis.del(key);
    }

    private Map<String,Integer> currentLockers(){
        Map<String, Integer> ref = lockers.get();
        if (ref != null){
            return ref;
        }
        lockers.set(new HashMap());
        return lockers.get();
    }

    public boolean lock(String key){
        Map<String, Integer> refs = currentLockers();
        Integer refCnt = refs.get(key);
        if (refCnt != null){
            refs.put(key,refCnt+1);
            return true;
        }
        boolean ok = this._lock(key);
        if (!ok) return false;
        refs.put(key,1);
        return true;
    }

    public boolean unlock(String key){
        Map<String, Integer> refs = currentLockers();
        Integer refCnt = refs.get(key);
        if (refCnt == null){
            return false;
        }
        refCnt -= -1;
        if (refCnt > 0){
            refs.put(key,refCnt);
        }else {
            refs.remove(key);
            this._unlock(key);
        }
        return true;
    }

    public static void main(String[] args) {
        Jedis jedis = jedisPool.getResource();
        RedisWithReentrantLock redis = new RedisWithReentrantLock(jedis);
        System.out.println(redis.lock("codehole"));
        System.out.println(redis.lock("codehole"));
        System.out.println(redis.unlock("codehole"));
        System.out.println(redis.unlock("codehole"));
        System.out.println(redis.unlock("codehole"));


    }

}
